
from ComDriver import ComDriver,BinConvert
import time
import json


def OnConReceive(r):
    ComDriver.responseStr=BinConvert.bytes2Str(r)

class Ggb():
    def __init__(self,port):
        self.comDriver= ComDriver(port,OnConReceive)
        self.comDriver.listen()


    def call(self,str):
        str="let ans="+str+";\n"
        str=str+""" WebSerialPlugin.sendStr(ans+"") """
        ComDriver.responseStr=""
        timeout=0;
        self.comDriver.SendStr(str)
        while ComDriver.responseStr=="" and timeout<15 :
            timeout=timeout+1;
            time.sleep(0.1);
        return ComDriver.responseStr
    

    
    def exec(self,str):
        self.comDriver.SendStr(str)
        return
    
    def getXcoord(self,point):
        r= self.call(f"""  ggb.getXcoord("{point}") """)
        r=float(r)
        return r
    
    def getYcoord(self,point):
        r= self.call(f"""  ggb.getYcoord("{point}") """)
        r=float(r)
        return r
    
    def getCoord(self,point):
        ComDriver.responseStr=""
        timeout=0
        self.comDriver.SendStr(f""" 
                                    let xval=  ggb.getXcoord("{point}") 
                                    let yval=  ggb.getYcoord("{point}") 
                                     WebSerialPlugin.sendStr(JSON.stringify([xval,yval]))
                                  """)
        while ComDriver.responseStr=="" and timeout<15 :
            timeout=timeout+1
            time.sleep(0.1)
        data = json.loads(ComDriver.responseStr)    
        return (data[0],data[1])
    
    def getValue(self,vname):
        r= self.call(f"""  ggb.getValue("{vname}") """)
        r=float(r)
        return r
    
    def setCoords(self,point,x,y):
        self.exec(f"""  ggb.setCoords("{point}",{x},{y}) """)
        return 
    
    def evalCommand(self,cmdStr):
        self.exec(f"""  ggb.evalCommand("{cmdStr}") """)
        return 
    
    def deleteObject(self,objName):
        self.exec(f"""  ggb.deleteObject({objName}) """)
        return 
    
    def reset(self):
        self.exec(f"""  ggb.reset() """)
        return 